<script lang="ts" setup>
import type { RoleApi } from '#/api/types';

import { useVbenDrawer } from '@vben/common-ui';

import { message } from 'ant-design-vue';

import { useVbenForm } from '#/adapter/form';
import { createRoleApi } from '#/api/core/modules/role';
import { $t } from '#/locales';

// 定义事件
const emit = defineEmits<{
  (e: 'success'): void;
}>();

// 创建表单
const [Form, formApi] = useVbenForm({
  schema: [
    {
      component: 'Input',
      fieldName: 'name',
      label: $t('system.role.roleName'),
      rules: 'required',
      componentProps: {
        placeholder: '请输入角色名称',
      },
    },
    {
      component: 'Input',
      fieldName: 'code',
      label: $t('system.role.code'),
      rules: 'required',
      componentProps: {
        placeholder: '请输入角色编码',
      },
    },
    {
      component: 'Textarea',
      fieldName: 'description',
      label: $t('system.role.remark'),
      componentProps: {
        placeholder: '请输入角色描述',
        rows: 4,
      },
    },
    {
      component: 'RadioGroup',
      componentProps: {
        buttonStyle: 'solid',
        options: [
          { label: $t('common.enabled'), value: 1 },
          { label: $t('common.disabled'), value: 0 },
        ],
        optionType: 'button',
      },
      defaultValue: 1,
      fieldName: 'status',
      label: $t('system.role.status'),
    },
    {
      component: 'InputNumber',
      fieldName: 'sort',
      label: '排序',
      defaultValue: 0,
      componentProps: {
        placeholder: '请输入排序值',
        min: 0,
      },
    },
  ],
  showDefaultActions: false,
});

// 抽屉组件
const [Drawer, drawerApi] = useVbenDrawer({
  title: $t('ui.actionTitle.create', [$t('system.role.name')]),

  // 表单确认处理
  async onConfirm() {
    try {
      // 表单验证
      const { valid } = await formApi.validate();
      if (!valid) return false;

      // 获取表单值
      const values = await formApi.getValues();

      // 锁定抽屉
      drawerApi.setState({ loading: true });

      // 创建角色
      const result = await createRoleApi(values as RoleApi.CreateParams);
      if (result.success) {
        message.success($t('common.operationSuccess'));
        emit('success');

        // 重置表单
        formApi.resetForm();

        // 主动关闭抽屉
        drawerApi.close();
        return true;
      } else {
        message.warning(result.message || $t('common.operationFailed'));
        return false;
      }
    } catch {
      return false;
    } finally {
      drawerApi.setState({ loading: false });
    }
  },

  // 打开关闭处理
  onOpenChange(isOpen) {
    if (isOpen) {
      // 重置表单
      formApi.resetForm();
    }
  },
});

// 暴露给父组件的API
defineExpose({
  drawerApi,
});
</script>
<template>
  <Drawer>
    <Form />
  </Drawer>
</template>
